<?php
// crontab -e   加入以下任务,每1分钟采集一次数据
// */1       *     *       *       *       /usr/local/bin/php /web/www/zlink/monitor/stats/collect.php
 

include __DIR__ . '/global.php';

$opts = [
    'table' => 'public.server',
    'where' => [
        'status' => ['<>', 0],
    ]
];

$model = new \Lib\Model;

if (!$records = $model->findAll($opts)) {
    exit();
}

$serverModel = new \Lib\Server;
$nginxModel  = new \Lib\Nginx;

foreach ($records as $row) {
    if (!$r = $serverModel->collect($row['collect_monitor_base_url'])) {
        continue;
    }

    $dao = [
        'id'   => $row['id'],
        'age'  => $r['age'],
        'server_time' => $r['time'],
        'last_collect_monitor_time' => date('Y-m-d H:i:s'),
    ];
    $dao['opts'] = $serverModel->buildJsonOpts([
        'id'  => $row['id'],
        'cpu' => $r['cpu'],
    ]);
    $serverModel->save($dao);

    $opts = [
        'table' => 'monitor.server',
        'dao'   => [
            'server_id'    => $row['id'],
            'load'         => $r['load'],
            'if_in'        => $r['if_in'],
            'if_out'       => $r['if_out'],
            'collect_time' => date('Y-m-d H:i:s'),
        ],
    ];
    $model->insert($opts);

    if (!$r = $nginxModel->collect($row['collect_monitor_base_url'])) {
        continue;
    }

    $dao = [
        'server_id'    => $row['id'],
        'val'          => $r,
        'collect_time' => date('Y-m-d H:i:s'),
    ];
    $nginxModel->insert(['dao' => $dao]);
}
